//? 定义初始状态
const initialState = {
    todos: [],
};
//? 定义 action 类型
const ADD_TODO = 'ADD_TODO';
//? 定义 action 创建函数
function addTodoAction(text) {
    return {
        type: ADD_TODO,
        payload: {
            text,
        },
    };
}
//? 定义 reducer 参数：state、action
function todosReducer(state = initialState, action) {
    switch (action.type) {
        //? 处理action:ADD_TODO
        case ADD_TODO:
            console.log({
                //? 这一步为了保留其他属性，只修改todos属性来覆盖原todos属性
                ...state,
                todos: [...state.todos, action.payload.text],
            })
            return {
                ...state,
                todos: [...state.todos, action.payload.text],
            };
        default:
            return state;
    }
}
//? 创建 store
let store = {
    state: initialState,
    //? 管理订阅者
    subscribers: [],
    getState() {
        return this.state;
    },
    //? 发送action
    dispatch(action) {
        this.state = todosReducer(this.state, action);
        //? 数据改变，调用订阅者回调函数
        this.subscribers.forEach((subscriber) => subscriber());
    },
    //? 订阅 将回调函数入栈
    subscribe(subscriber) {
        this.subscribers.push(subscriber);
    },
};
//? 订阅 state 变化
store.subscribe(() => {
    console.log(store.getState());
});
//? 分发 action
store.dispatch(addTodoAction('学习 Redux'));
// store.dispatch(addTodoAction('编写示例代码'));
